package com.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.constant.MessageConstant;
import com.dto.MaterialInputExcelModel;
import com.dto.MaterialInputExportModel;
import com.dto.MaterialInputSearchForm;
import com.entity.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mapper.*;
import com.result.Result;
import com.service.MaterialInputService;
import com.utils.CommonUtils;
import com.utils.CustomCellWriteHandler;
import com.utils.PageObject;
import net.sf.cglib.core.Local;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  物料输入服务实现类
 * </p>
 *
 * @author aiou
 * @since 2025-06-08
 */
@Service
public class MaterialInputServiceImpl implements MaterialInputService {

    @Autowired
    private MaterialInputMapper materialInputMapper;

    @Autowired
    private SupplierMapper supplierMapper;

    @Autowired
    private StorageMapper storageMapper;

    @Autowired
    private MaterialMapper materialMapper;

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;


    /**
     * Excel导入
     */
    @Override
    public Result<String> excelImport(InputStream inputStream) {
        //todo:1、easyExcel解析Excel导入MaterialInputExcelModel类中
        ArrayList<MaterialInputExcelModel> list = new ArrayList<>();
        try (InputStream is = inputStream) {  // 使用 try-with-resources 确保流被关闭
            EasyExcel.read(is)
                    .head(MaterialInputExcelModel.class)
                    .sheet()
                    //监听Excel中每一行数据
                    .registerReadListener(new AnalysisEventListener<MaterialInputExcelModel>() {
                        //解析时操作
                        @Override
                        public void invoke(MaterialInputExcelModel excelData, AnalysisContext analysisContext) {
                            list.add(excelData);
                        }

                        //解析后操作
                        @Override
                        public void doAfterAllAnalysed(AnalysisContext analysisContext) {

                        }
                    }).doRead();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(MessageConstant.EXCEL_ANYLIS_ERROR +":"+ e.getMessage());
        }

        //todo:2、封装MaterialInput类
        int row =0;
        for (MaterialInputExcelModel materialInputExcelModel : list) {
            row++;
            //todo:2.1、将MaterialInputExcelModel中数据赋值给MaterialInput
            MaterialInput materialInput = new MaterialInput();
            BeanUtils.copyProperties(materialInputExcelModel, materialInput);
            //todo:2.2、MaterialInputExcelModel中的orderDate和MaterialInput中的orderDate类型不一样，需转换
            LocalDateTime orderDate = CommonUtils.parseString(materialInputExcelModel.getOrderDate());
            materialInput.setOrderDate(orderDate);
            //todo:2.3、补充MaterialInput类中缺失的物料Id、供应商名称和Id、仓库名称和Id、操作用户名称
            //获取物料Id，并判断物料是否为空，若为空，报错
            Integer materialId = materialMapper.selectAllByCode(materialInputExcelModel.getMaterialCode()).getMaterialId();
            if (materialId == null){
                return Result.error("第"+row+"行错误:"+MessageConstant.MATERIAL_NOT_EXIST);
            }
            materialInput.setMaterialId(materialId);
            //获取供应商名称和Id,并判断供应商是否为空，若为空，报错
            Supplier supplier = supplierMapper.selectAllByCode(materialInputExcelModel.getSupplierCode());
            if (supplier == null){
                return Result.error("第"+row+"行错误:"+MessageConstant.SUPPLIER_NOT_EXIST);
            }
            materialInput.setSupplierId(supplier.getSupplierId());
            materialInput.setSupplierName(supplier.getSupplierName());
            //获取仓库名称和Id,并判断仓库是否为空，若为空，报错
            Storage storage = storageMapper.selectAllByCode(materialInputExcelModel.getStorageCode());
            if (storage == null){
                return Result.error("第"+row+"行错误:"+MessageConstant.STORAGE_NOT_EXIST);
            }
            materialInput.setStorageId(storage.getStorageId());
            materialInput.setStorageName(storage.getStorageName());
            //假设用户名称和审核状态
            materialInput.setUserName("张三");
            materialInput.setStatus(0);
            //todo:3、判断序列号batch_no是否相同，若相同且审核状态不是已审核，则做更新操作
            if (materialInputMapper.selectByBatchNo(materialInput.getBatchNo()) != null
                && materialInputMapper.selectByBatchNo(materialInput.getBatchNo()).getStatus() == 0){
                boolean updateResult = materialInputMapper.updateByBatchNo(materialInput);
                if (!updateResult){
                    return Result.error("第"+row+"行错误:"+MessageConstant.UPDATE_ERROR);
                }
            }else{
                //todo:4、将MateralInput插入material_input表
                Boolean insertResult = materialInputMapper.insert(materialInput);
                if (!insertResult) {
                    return Result.error("第"+row+"行错误:"+MessageConstant.INSERT_ERROR);
                }
            }
        }
        return Result.success(MessageConstant.IMPORT_SUCCESS);
    }

    /**
     * 获取列表
     */
    @Override
    public PageObject<MaterialInput> list(PageObject pageObject, MaterialInputSearchForm form) {

        //开始分页
        PageHelper.startPage(pageObject.getCurrent(),pageObject.getSize());
        //查询数据
        List<MaterialInput> list = materialInputMapper.list(form);
        //PageHelper包装数据
        PageInfo<MaterialInput> pageInfo = new PageInfo<>(list);
        //将数据封装进PageResult
        PageObject<MaterialInput> userPageResult
                = new PageObject<>(pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal(), pageInfo.getList());
        return userPageResult;
    }

    /**
     * 获取导出列表
     */
    @Override
    public Result<String> excelOutput(HttpServletResponse response) {
        //todo:1、查询所有数据
        List<MaterialInput> materialInputs = materialInputMapper.selectAll();
        ArrayList<MaterialInputExportModel> list = new ArrayList<>();
        //todo:2、封装数据到 List<MaterialInputExportModel>
        for (MaterialInput materialInput : materialInputs) {
            MaterialInputExportModel model = new MaterialInputExportModel();
            BeanUtils.copyProperties(materialInput, model);
            //日期
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            model.setOrderDate(materialInput.getOrderDate().format(dateTimeFormatter));
            //状态
            String status = "";
            switch (materialInput.getStatus()){
                case 0:
                    status = "待审核";
                    break;
                case 1:
                    status = "审核通过";
                    break;
                case 2:
                    status = "审核未通过";
                    break;
            }
            model.setStatus(status);
            list.add(model);
        }
        //todo:3、导出数据
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            String fileName = URLEncoder.encode("采购数据", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            //获取数据
            EasyExcel.write(response.getOutputStream(), MaterialInputExportModel.class)
                    .registerWriteHandler(new CustomCellWriteHandler())
                    .sheet("采购数据")
                    .doWrite(list);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error(MessageConstant.EXPORT_ERROR+":"+e.getMessage());
        }
        return Result.success(MessageConstant.EXPORT_SUCCESS);
    }

    /**
     * 批量审核接口
     */
    @Override
    @Transactional
    public boolean verify(Integer status, String idArray) {
        boolean flag = false;
        String[] ids = idArray.split(",");
        switch (status){
            case 1:
                //审核
                List<Integer> idList = new ArrayList<>();
                for (String id : ids) {
                    idList.add(Integer.parseInt(id));
                }
                boolean verify = this.materialInputMapper.verify(idList,status);
                if(!verify) return false;
                flag = true;
                break;
            case 2:
                //入库
                for (String id : ids) {
                    MaterialInput materialInput = materialInputMapper.selectById(id);
                    //todo:1、将数据同步到Orders
                    Orders orders = new Orders();
                    BeanUtils.copyProperties(materialInput,orders);
                    //统计订单数量，作为订单后缀
                    Integer count = ordersMapper.selectCount();
                    orders.setOrderNo(CommonUtils.createOrderNo(count,1));
                    orders.setInvalid(1);
                    orders.setVerifyPerson("李四");
                    orders.setVerifyDate(LocalDateTime.now());
                    orders.setEmployeeName(materialInput.getUserName());
                    orders.setOrderType(1);
                    int orderInsertResult =ordersMapper.insert(orders);
                    if (orderInsertResult != 1 ) return false;
                    //todo:2、将数据同步到OrderDetail
                    OrderDetail orderDetail = new OrderDetail();
                    BeanUtils.copyProperties(materialInput,orderDetail);
                    orderDetail.setOrderNo(orders.getOrderNo());
                    orderDetail.setOrderFlag("正常");
                    int orderDetailsInsertResult = orderDetailMapper.insert(orderDetail);
                    if(orderDetailsInsertResult != 1) return false;
                    //todo:3、修改MaterialInput为已入库状态
                    materialInput.setStatus(status);
                    materialInput.setOrderNo(orders.getOrderNo());
                    int updateById = materialInputMapper.updateById(materialInput);
                    if(updateById != 1) return false;
                }
                flag = true;
                break;
        }
        return flag;
        }

    /**
     * 删除物料清单
     * @param idArray
     * @return
     */
    @Override
    public boolean delete(String idArray) {
        String[] ids = idArray.split(",");
        List<Integer> idList = new ArrayList<>();
        for (String id : ids) {
            idList.add(Integer.parseInt(id));
        }
        boolean deleteResult = materialInputMapper.deleteById(idList);
        return deleteResult;
    }
}

